package cn.zl.springbootmqtt.sub;

import cn.zl.springbootmqtt.entity.AlertInfo;
import cn.zl.springbootmqtt.entity.DeviceStatus;
import cn.zl.springbootmqtt.mapper.AlertInfoMapper;
import cn.zl.springbootmqtt.mapper.DeviceMapper;
import cn.zl.springbootmqtt.service.DeviceService;
import cn.zl.springbootmqtt.util.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @Description:MQTT订阅回调类
 * @Author: zhanglang
 * @Date: 2020/10/27 14:55
 */
//@Component
public class SubCallBack implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(SubCallBack.class);

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private AlertInfoMapper alertInfoMapper;
    /**
     * 连接丢失，用于重连
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("连接已断开，尝试重新连接。。。");
    }

    /**
     * 消息已经送达，接收到消息
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        System.out.println("接收消息主题 : " + topic);
        System.out.println("接收消息Qos : " + mqttMessage.getQos());
        System.out.println("接收消息内容 : " + new String(mqttMessage.getPayload()));
        Queue<byte[]> q = new LinkedList<byte[]>();
        q.add(mqttMessage.getPayload()); //放入队列
        byte[] c = q.peek(); //取得队头元素
        String res = new String(c);//使用构造函数转换成字符串
        AlertInfo alertInfo = JSONObject.parseObject(res , AlertInfo.class);
        System.out.println(alertInfo);
        if (alertInfo != null){
            try {
                alertInfoMapper = BeanUtil.getBean(AlertInfoMapper.class);
                alertInfoMapper.insert(alertInfo);
            }catch (Exception e){
                e.printStackTrace();
                logger.debug("error");
            }
        }else {
            System.out.println("device的值为null");
        }
    }
    /**
     * publish后会执行到这里，发送的状态
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println("deliveryComplete..." + iMqttDeliveryToken.isComplete());
    }
}